package cn.gdust.servlet;

import cn.gdust.dao.CommentDao;
import cn.gdust.entity.Comment;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/CommentServlet.do")
public class CommentServlet extends HttpServlet {
 @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

            try {
                // 获取视频id
                String vId = request.getParameter("video_id");
                // 创建评论数据访问对象
                CommentDao commentDao = new CommentDao();
                // 查询所有评论
                List<Comment> comments = commentDao.findAll(vId);
                // 创建Gson对象
                Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
                // 将评论转换为json格式
                String json = gson.toJson(comments);
                // 设置响应类型和编码
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                // 将json数据写入响应
                response.getWriter().write(json);
            } catch (SQLException e) {
              e.printStackTrace();
            }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        super.doGet(request, response);
    }
}
